package com.ykq.service.impl;

import com.ykq.dao.PermissionMapper;
import com.ykq.entity.EmpInfo;
import com.ykq.entity.Permission;
import com.ykq.service.PermissionService;
import com.ykq.vo.FenPermissionVo;
import com.ykq.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: qy174-mrcai
 * @description:
 * @author: 闫克起
 * @create: 2024-06-05 10:00
 **/
@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private HttpSession session;

    public R findByEmpId() {
        EmpInfo empinfo = (EmpInfo) session.getAttribute("empinfo");
        List<Permission> permissions = permissionMapper.selectByEmpId(empinfo.getId());
        //父子关系的结构---获取一级菜单
        List<Permission> first = new ArrayList<Permission>();
        //遍历菜单
        for (Permission p : permissions) {
            //表示一级菜
            if (p.getPid().equals(0L)) {
                first.add(p);
            }
        }
        //查询一级菜单下对应的二级菜单====一级菜单下的id===二级菜单的父id  pid
        for (Permission f : first) {
            List<Permission> children = new ArrayList<Permission>();
            for (Permission p : permissions) {
                if (p.getPid().equals(f.getId())) {
                    children.add(p);
                }
            }
            f.setChildren(children);
        }
        return new R(2000, "查询左侧菜单成功", first);
    }

    public R selectByRoleId(Integer roleId) {
        //查询所有的权限
        List<Permission> permissions = permissionMapper.selectAll();
        //查询以及菜单
        List<Permission> first = new ArrayList<Permission>();
        for (Permission f : permissions) {
            if (f.getPid().equals(0L)) {
                first.add(f);
            }
        }
        //2.查询一级菜单下的二级菜单
        for (Permission f : first) {
            List<Permission> children = new ArrayList<Permission>();
            for (Permission p : permissions) {
                if (p.getPid().equals(f.getId())) {
                    children.add(p);
                }
            }
            f.setChildren(children);
        }

        //3.当前角色具有的权限id
        List<Long> permissionIds = permissionMapper.selectPidByRoleId(roleId);

        //map  vo=====>
        FenPermissionVo permissionVo=new FenPermissionVo(first,permissionIds);
        return new R(2000,"查询成功",permissionVo);
    }

    public R qrFen(Integer rid, Long[] checkIds) {
         //1.删除该角色具有的权限
       int row= permissionMapper.deleteByRoleId(rid);
        //2.重新添加新的权限
        int row2=permissionMapper.batchInsert(rid,checkIds);
        return new R(2000,"分配权限成功");
    }
}




























